package com.key.modules.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.key.common.base.RespResult;
import com.key.common.constants.Constants;
import com.key.component.jwt.JwtUtil;
import com.key.modules.dto.LoginFormDTO;
import com.key.modules.dto.SysUserSelectDTO;
import com.key.modules.entity.SysUser;
import com.key.modules.mapper.SysUserMapper;
import com.key.modules.service.SysUserService;
import com.key.modules.vo.IndentVO;
import com.key.modules.vo.SysUserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @Author：朕
 * @Package：com.key.modules.service.impl
 * @Project：logistics_system
 * @name：SysUserServiceImpl
 * @Date：2023/3/23 20:03
 * @Filename：SysUserServiceImpl
 */
@Service
@Slf4j
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public RespResult login(LoginFormDTO loginFormDTO,HttpServletResponse response) {
        log.info("进入登录");
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginFormDTO.getUsername(),loginFormDTO.getPassword());
            log.info("账户："+loginFormDTO.getUsername());
            log.info("密码："+loginFormDTO.getPassword());
            //登录
            subject.login(usernamePasswordToken);
            //将登录成功后的用户信息存入sesssion中
            subject.getSession().setAttribute("account",loginFormDTO.getUsername());

            System.out.println("==登录成功后获取账户信息==="+SecurityUtils.getSubject().getSession().getAttribute("account"));
            // 生成对应的Token
            String token =  JwtUtil.createToken(UUID.randomUUID().toString(), Constants.SECRET,loginFormDTO.getUsername(),60*60*1000);
            // 通过响应头返回给前端
            response.addHeader("token",token);
            return RespResult.success();
        }  catch (UnknownAccountException e){
            log.error("账户有误");
            return RespResult.error("账户有误");
        }catch (IncorrectCredentialsException e){
            log.error("密码有误");
            return RespResult.error("密码有误");
        }catch (LockedAccountException e){
            log.error("{}账户被冻结",loginFormDTO.getUsername());
            return RespResult.error("账户被冻结");
        }catch (AuthenticationException e){
            log.error("{}认证错误",loginFormDTO);
            return RespResult.error("认证错误");
        }
    }


    /**
     * 显示用户信息
     * @return
     */
    @Override
    public List<SysUserVO> findSysUser(SysUserSelectDTO sysUserSelectDTO) {
        log.info("显示用户信息+分页："+sysUserSelectDTO);
//        Long l = Long.valueOf(sysUserSelectDTO.getCurrent().toString());
//        Long l1 = Long.valueOf(sysUserSelectDTO.getSize().toString());
        Page<SysUserSelectDTO> page =new Page<>(sysUserSelectDTO.getCurrent(),sysUserSelectDTO.getSize());
        List<SysUserVO> sysUserVOS = sysUserMapper.findSysUser(page);
        log.info("显示成功");
        return sysUserVOS;
    }

    /**
     * 新增用户
     * @param sysUser
     * @return
     */
    @Override
    public Boolean addSysUser(SysUser sysUser) {
        log.info("用户信息",sysUser);
        int s1 = 0;
        Date date = new Date();
        //设置当前创建时间
        sysUser.setUserDate(date);
        //设置用户修改时间为null
        sysUser.setUserUpdateDate(null);
        //根据用户账号查询数据库中是否有该用户，必免重复添加
        SysUser s = sysUserMapper.selectByAccount(sysUser.getUserAccount());
        if (s == null) {
            //增加用户
            s1 = sysUserMapper.insert(sysUser);
            log.info("增加成功:"+s1);
            if(s1>0){
                return true;
            }
        }
        log.info("增加失败:"+s1);
        return false;
    }

    /**
     * 修改用户
     * @param sysUser
     * @return
     */
    @Override
    public Boolean updateSysUser(SysUser sysUser) {
        log.info("用户信息",sysUser);
        Date date = new Date();
        //设置当前修改时间
        sysUser.setUserUpdateDate(date);
        sysUser.setUserDate(null);
        int s = sysUserMapper.updateById(sysUser);
        if(s>0){
            log.info("修改成功:"+s);
            return true;
        }
        log.info("修改失败:"+s);
        return false;
    }

    /**
     * 删除用户
     * @param userId
     * @return
     */
    @Override
    public Boolean deleteSysUser(Integer userId) {
        log.info("用户id:"+userId);
        int s = sysUserMapper.deleteById(userId);
        if(s>0){
            log.info("删除成功:"+s);
            return true;
        }
        log.info("删除失败:"+s);
        return false;
    }

    /**
     * 增加用户角色
     * @param roleId
     * @return
     */
    @Override
    public Boolean addSysUserRole(Integer userId,Integer[] roleId) {
        for(int j =0;j<roleId.length;j++) {
            log.info("用户id:" + userId, "角色Id:" + roleId);
        }
        int s = 0;
        Map<String,Object> map = new HashMap();
        sysUserMapper.deleteRoleIdByUserId(userId);
        for(int i = 0;i<roleId.length;i++){
            map.put("userId",userId);
            map.put("roleId",roleId[i]);
             s = sysUserMapper.addRoleIdByUserId(map);
        }
        if(s>0){
            log.info("角色添加成功:"+s);
            return true;
        }
        log.info("角色添加失败:"+s);
        return false;
    }
}
